use std::collections::HashSet;
use argon2::{Argon2, PasswordHash, PasswordHasher, PasswordVerifier};
use argon2::password_hash::rand_core::OsRng;
use argon2::password_hash::SaltString;
use sea_orm::{ColumnTrait, Set, TransactionTrait};
use sea_orm::{DatabaseConnection, EntityTrait, QueryFilter};
use crate::entity::{sys_auth_authority, sys_auth_role_authority_r, user_main, user_notification, user_wallet_bill};
use crate::entity::user_account;
use crate::entity::user_cart;
use crate::entity::user_address;
use crate::entity::user_auth_authority;
use crate::entity::user_auth_role;
use crate::entity::user_collection;
use crate::entity::user_wallet;
use async_graphql::Result as GraphQLResult;
use chrono::Duration;
use redis::aio::MultiplexedConnection;
use snowid::SnowID;
use sqlx::types::chrono::Utc;
use sqlx::types::Decimal;
use tracing::{debug, warn};
use crate::graphql::user_graphql::{LoginUserInput, RegisterUserInput, UpdateUserInput, UserAccountInput, UserAccountObject, UserAddressInput, UserAddressObject, UserAuthorityObject, UserCartItemObject, UserCollectionObject, UserLoginObject, UserObject, UserRoleObject, UserTokenObject, UserWalletObject};
use crate::utility::jwt::{AccessClaims, Claims, JwtUtil, RefreshClaims};


pub async fn get_users(
    db: &DatabaseConnection,
    conn: &MultiplexedConnection,
) -> GraphQLResult<Option<Vec<UserObject>>> {
    // 尝试从缓存获取
    let cached_result: Option<String> =
        redis::cmd("GET")
            .arg("user_list")
            .query_async(&mut conn.clone())
            .await?;

    if let Some(cached_data) = cached_result {
        // 如果缓存中有数据，直接返回
        return Ok(Some(serde_json::from_str::<Vec<UserObject>>(&cached_data)?));
    }

    let user_models = user_main::Entity::find()
        .all(db)
        .await?;

    if user_models.is_empty() {
        return Ok(None);
    }

    let mut user_objects = Vec::new();

    for user in user_models {
        if let Some(user_object) = get_user_by_id(db, user.id.to_string()).await? {
            user_objects.push(user_object);
        }
    }

    // 将数据序列化为 JSON 字符串后存入 Redis
    let json_data = serde_json::to_string(&user_objects)?;

    // 异步设置缓存，设置过期时间（例如：300秒）
    redis::cmd("SETEX")
        .arg("user_list")
        .arg(300) // 5分钟过期
        .arg(&json_data)
        .query_async::<()>(&mut conn.clone())
        .await?;

    Ok(Some(user_objects))
}
pub async fn get_user_by_id(
    db: &DatabaseConnection,
    user_id: String,
) -> GraphQLResult<Option<UserObject>> {

    let user_id: u64 = user_id.parse().map_err(|_| async_graphql::Error::new("Invalid user ID"))?;

    // 查询用户主信息
    let user = user_main::Entity::find_by_id(user_id)
        .one(db)
        .await?;

    if let Some(user) = user {
        // 查询用户账户信息
        let accounts = user_account::Entity::find()
            .filter(user_account::Column::UserId.eq(user_id))
            .all(db)
            .await?
            .into_iter()
            .map(UserAccountObject::from)
            .collect();

        // 查询用户直接关联的权限（如果没有角色-权限关联表）
        let authorities = user_auth_authority::Entity::find()
            .filter(user_auth_authority::Column::UserId.eq(user_id))
            .all(db)
            .await?
            .into_iter()
            .map(|authority| UserAuthorityObject {
                id: authority.id.to_string(),
                user_id: authority.user_id.to_string(),
                authority_id: authority.authority_id.to_string(),
                name: authority.name,
                create_time: authority.create_time.format("%Y-%m-%d %H:%M:%S").to_string(),
                update_time: authority.update_time.format("%Y-%m-%d %H:%M:%S").to_string(),
            })
            .collect();

        // 查询用户地址信息
        let addresses = user_address::Entity::find()
            .filter(user_address::Column::UserId.eq(user_id))
            .all(db)
            .await?
            .into_iter()
            .map(|address| UserAddressObject {
                id: address.id.to_string(),
                user_id: address.user_id.to_string(),
                recipient_name: address.recipient_name,
                phone: address.phone,
                province: address.province,
                city: address.city,
                district: address.district,
                detail: address.detail,
                is_default: address.is_default != 0,
                tag: address.tag,
                create_time: address.create_time.format("%Y-%m-%d %H:%M:%S").to_string(),
                update_time: address.update_time.format("%Y-%m-%d %H:%M:%S").to_string(),
            })
            .collect();

        // 查询用户角色信息（简化处理，实际应通过关联表查询）
        let roles = user_auth_role::Entity::find()
            .filter(user_auth_role::Column::UserId.eq(user_id)) // 示例：假设用户有角色1
            .all(db)
            .await?
            .into_iter()
            .map(UserRoleObject::from)
            .collect();

        // 查询用户购物车信息
        let cart_items = user_cart::Entity::find()
            .filter(user_cart::Column::UserId.eq(user_id))
            .all(db)
            .await?
            .into_iter()
            .map(|cart_item| UserCartItemObject {
                id: cart_item.id.to_string(),
                user_id: cart_item.user_id.to_string(),
                product_id: cart_item.product_id.to_string(),
                quantity: cart_item.quantity,
                create_time: cart_item.create_time.format("%Y-%m-%d %H:%M:%S").to_string(),
                update_time: cart_item.update_time.format("%Y-%m-%d %H:%M:%S").to_string(),
            })
            .collect();

        // 查询用户收藏信息
        let collections = user_collection::Entity::find()
            .filter(user_collection::Column::UserId.eq(user_id))
            .all(db)
            .await?
            .into_iter()
            .map(|collection| UserCollectionObject {
                id: collection.id.to_string(),
                user_id: collection.user_id.to_string(),
                product_id: collection.product_id.to_string(),
                create_time: collection.create_time.format("%Y-%m-%d %H:%M:%S").to_string(),
                update_time: collection.update_time.format("%Y-%m-%d %H:%M:%S").to_string(),
            })
            .collect();

        // 查询用户钱包信息
        let wallet = user_wallet::Entity::find()
            .filter(user_wallet::Column::UserId.eq(user_id))
            .one(db)
            .await?
            .map(|wallet| UserWalletObject {
                id: wallet.id.to_string(),
                user_id: wallet.user_id.to_string(),
                balance: wallet.balance.to_string(),
                create_time: wallet.create_time.format("%Y-%m-%d %H:%M:%S").to_string(),
                update_time: wallet.update_time.format("%Y-%m-%d %H:%M:%S").to_string(),
            });

        Ok(Some(UserObject {
            id: user.id.to_string(),
            username: user.username,
            nickname: user.nickname,
            avatar_addr: user.avatar_addr,
            status: user.status,
            create_time: user.create_time.format("%Y-%m-%d %H:%M:%S").to_string(),
            update_time: user.update_time.format("%Y-%m-%d %H:%M:%S").to_string(),
            accounts,
            addresses,
            roles,
            authorities,
            cart_items,
            collections,
            wallet,
        }))
    } else {
        Ok(None)
    }
}

pub async fn registry_user_form(db: &DatabaseConnection,conn : &MultiplexedConnection, input: RegisterUserInput)
     -> GraphQLResult<UserLoginObject>
{
    // 开启事务
    let txn = db.begin().await.map_err(|e| async_graphql::Error::new(format!("开启事务失败: {}", e)))?;



    // 检查用户名是否已存在
    let existing_user = user_main::Entity::find()
        .filter(user_main::Column::Username.eq(&input.username))
        .one(&txn)
        .await
        .map_err(|e| async_graphql::Error::new(format!("查询用户失败: {}", e)))?;

    // 如果提供了邮箱，检查邮箱是否已存在
    if let Some(ref email) = input.email {
        let existing_email_account = user_account::Entity::find()
            .filter(user_account::Column::Type.eq("email"))
            .filter(user_account::Column::Account.eq(email))
            .one(&txn)
            .await
            .map_err(|e| async_graphql::Error::new(format!("查询邮箱失败: {}", e)))?;

        if existing_email_account.is_some() {
            return Err(async_graphql::Error::new("邮箱已被使用"));
        }
    }

    if existing_user.is_some() {
        return Err(async_graphql::Error::new("用户名已存在"));
    }

    // 生成盐值并哈希密码
    let salt = SaltString::generate(&mut OsRng);
    let argon2 = Argon2::default();
    let password_hash = argon2
        .hash_password(input.password.as_bytes(), &salt)
        .map_err(|e| async_graphql::Error::new(format!("密码处理失败: {}", e)))?
        .to_string();

    let now = Utc::now().naive_utc();

    let sn = SnowID::new(1)?;
    let id = sn.generate();
    // 创建用户主信息
    let new_user = user_main::ActiveModel {
        id: Set(id),
        username: Set(input.username.clone()),
        password: Set(Option::from(password_hash.clone())),
        nickname: Set(input.nickname.clone().unwrap_or_else(|| input.username.clone())),
        avatar_addr: Set(input.avatar_addr.clone().unwrap_or_default()),
        status: Set("active".to_string()),
        create_time: Set(now),
        update_time: Set(now),
    };

    let inserted_user = user_main::Entity::insert(new_user)
        .exec_with_returning(&txn)
        .await
        .map_err(|e| async_graphql::Error::new(format!("创建用户失败: {}", e)))?;

    // 如果提供了邮箱，创建邮箱账户记录
    let mut accounts: Vec<UserAccountObject> = vec![];

    if let Some(ref email) = input.email {
        let email_account = user_account::ActiveModel {
            id: Set(sn.generate()),
            user_id: Set(id),
            r#type: Set("email".to_string()),
            account: Set(email.clone()),
            access_code: Set(None),
            create_time: Set(now),
            update_time: Set(now),
        };

        let inserted_account = user_account::Entity::insert(email_account)
            .exec_with_returning(&txn)
            .await
            .map_err(|e| {
                async_graphql::Error::new(format!("创建邮箱账户失败: {}", e))
            })?;

        // 添加到返回的账户列表中
        accounts.push(UserAccountObject::from(inserted_account));
    }

    // 提交事务
    txn.commit().await.map_err(|e| async_graphql::Error::new(format!("提交事务失败: {}", e)))?;



    // 构建返回的用户对象
    let mut user_object = UserLoginObject {
        id: inserted_user.id.to_string(),
        username: inserted_user.username,
        nickname: inserted_user.nickname,
        avatar_addr: inserted_user.avatar_addr,
        status: inserted_user.status,
        create_time: inserted_user.create_time.format("%Y-%m-%d %H:%M:%S").to_string(),
        update_time: inserted_user.update_time.format("%Y-%m-%d %H:%M:%S").to_string(),
        accounts,
        access_token: "".to_string(),
        refresh_token: "".to_string(),
        authorities: vec![],
        roles: vec![],
    };

    let jti = sn.generate();

    // 生成JWT令牌，有效期24小时
    let access_token = JwtUtil::generate_token(AccessClaims {
        u: inserted_user.id,
        e: (Utc::now() + Duration::minutes(30)).timestamp() as u32,
        a: HashSet::from([]),
    })?;

    let refresh_token = JwtUtil::generate_token(RefreshClaims {
        u: inserted_user.id,
        e: (Utc::now() + Duration::days(7)).timestamp() as u32,
        j: jti.clone(),
    })?;

    user_object.access_token = access_token;
    user_object.refresh_token = refresh_token;

    // 将用户ID和refresh_token保存到Redis

    let redis_key = format!("user:login:{}", user_object.id.to_string());

    // 设置过期时间（例如7天）
    let expire_seconds = 7 * 24 * 60 * 60; // 7天

    // 使用low-level命令设置key-value对并设置过期时间
    redis::cmd("SETEX")
        .arg(&redis_key)
        .arg(expire_seconds)
        .arg(&jti)
        .query_async::<()>(&mut conn.clone())
        .await
        .map_err(|e| async_graphql::Error::new(format!("保存jti到Redis失败: {}", e)))?;

    Ok(user_object)
}

pub async fn login(
    db: &DatabaseConnection,
    conn: &MultiplexedConnection,
    input: LoginUserInput,
) -> GraphQLResult<UserLoginObject> {
    // 查找用户
    let user = user_main::Entity::find()
        .filter(user_main::Column::Username.eq(&input.username))
        .one(db)
        .await
        .map_err(|e| async_graphql::Error::new(format!("查询用户失败: {}", e)))?
        .ok_or_else(|| async_graphql::Error::new("用户不存在"))?;

    // 验证密码
    let password = user.password.ok_or_else(|| async_graphql::Error::new("用户密码未设置"))?;

    let parsed_hash = PasswordHash::new(&password)
        .map_err(|_| async_graphql::Error::new("密码格式错误"))?;

    let argon2 = Argon2::default();
    argon2
        .verify_password(input.password.as_bytes(), &parsed_hash)
        .map_err(|_| async_graphql::Error::new("用户名或密码错误"))?;

    let login_key = format!("user:login:{}", user.id.to_string());

    let jti = redis::cmd("GET")
        .arg(&login_key)
        .query_async::<Option<String>>(&mut conn.clone())
        .await
        .map_err(|e| async_graphql::Error::new(format!("从Redis获取jti失败: {}", e)))?;

    if jti.is_some() {
        redis::cmd("DEL")
        .arg(&login_key)
        .query_async::<()>(&mut conn.clone())
        .await
        .map_err(|e| async_graphql::Error::new(format!("从Redis删除jti失败: {}", e)))?;
    }

    // 查询用户直接关联的权限（如果没有角色-权限关联表）
    let authorities = user_auth_authority::Entity::find()
        .filter(user_auth_authority::Column::UserId.eq(user.id))
        .all(db)
        .await?
        .into_iter()
        .map(|authority| UserAuthorityObject {
            id: authority.id.to_string(),
            user_id: authority.user_id.to_string(),
            name: authority.name,
            create_time: authority.create_time.format("%Y-%m-%d %H:%M:%S").to_string(),
            update_time: authority.update_time.format("%Y-%m-%d %H:%M:%S").to_string(),
            authority_id: authority.authority_id.to_string(),
        })
        .collect::<Vec<UserAuthorityObject>>();

    // 查询用户角色信息（简化处理，实际应通过关联表查询）
    let roles = user_auth_role::Entity::find()
        .filter(user_auth_role::Column::UserId.eq(user.id)) // 示例：假设用户有角色1
        .all(db)
        .await?
        .into_iter()
        .map(UserRoleObject::from)
        .collect::<Vec<UserRoleObject>>();



    // 将权限名称添加到HashSet中
    // 新增代码：将权限名称保存到 authority_names 集合中
    let mut authority_names: HashSet<String> = HashSet::new();

    authorities.iter().for_each(|authority| {
        authority_names.insert(authority.name.clone());
    });

    // 遍历每个角色，查询其对应的权限
    for role in &roles {
        // 将角色ID从字符串转换为u64
        // 替换原396行开始的代码段如下：
        let role_authority_relations = sys_auth_role_authority_r::Entity::find()
            .filter(sys_auth_role_authority_r::Column::RoleId.eq(role.id.clone()))
            .all(db)
            .await?;

        let authority_ids: Vec<u64> = role_authority_relations
            .iter()
            .map(|r| r.authority_id)
            .collect();

        let role_authorities = sys_auth_authority::Entity::find()
            .filter(sys_auth_authority::Column::Id.is_in(authority_ids))
            .all(db)
            .await?
            .into_iter()
            .map(|authority| authority.authority_name)
            .collect::<HashSet<String>>();
        

        authority_names.extend(role_authorities);
        
    }


    // 获取用户账户信息
    let accounts: Vec<UserAccountObject> = user_account::Entity::find()
        .filter(user_account::Column::UserId.eq(user.id))
        .all(db)
        .await
        .map_err(|e| async_graphql::Error::new(format!("查询用户账户失败: {}", e)))?
        .into_iter()
        .map(UserAccountObject::from)
        .collect();



    let jti = SnowID::new(1)?.generate();
    
    

    // 生成JWT令牌，有效期24小时
    let access_token = JwtUtil::generate_token(AccessClaims {
        u: user.id,
        e: (Utc::now() + Duration::minutes(30)).timestamp() as u32,
        a: authority_names,
    })?;

    let refresh_token = JwtUtil::generate_token(RefreshClaims {
        u: user.id,
        e: (Utc::now() + Duration::days(7)).timestamp() as u32,
        j: jti.clone(),
    })?;
    
    // 将用户ID和refresh_token jti保存到Redis
    // 设置过期时间（例如7天）
    let expire_seconds = 7 * 24 * 60 * 60; // 7天

    // 使用low-level命令设置key-value对并设置过期时间
    redis::cmd("SETEX")
        .arg(&login_key)
        .arg(expire_seconds)
        .arg(&jti)
        .query_async::<()>(&mut conn.clone())
        .await
        .map_err(|e| async_graphql::Error::new(format!("保存jti到Redis失败: {}", e)))?;


    // 构建UserLoginObject
    let user_login_object = UserLoginObject {
        id: user.id.to_string(),
        username: user.username,
        nickname: user.nickname,
        avatar_addr: user.avatar_addr,
        roles,
        authorities,
        status: user.status,
        accounts: accounts.clone(),
        access_token: access_token.clone(), // 先留空，后面会填充
        refresh_token: refresh_token.clone(), // 先留空，后面会填充
        create_time: user.create_time.format("%Y-%m-%d %H:%M:%S").to_string(),
        update_time: user.update_time.format("%Y-%m-%d %H:%M:%S").to_string(),
    };
    
    Ok(user_login_object)
}

pub async fn delete_user(db: &DatabaseConnection,
                         conn: &MultiplexedConnection,
                         user_id: String)
    -> GraphQLResult<bool> {
    // 开启事务
    let txn = db.begin().await
        .map_err(|e| async_graphql::Error::new(format!("开启事务失败: {}", e)))?;

    // 删除用户相关的所有数据
    let user_id: u64 = user_id.parse()
        .map_err(|_| async_graphql::Error::new("无效的用户ID"))?;

    // 1. 删除用户账户信息
    user_account::Entity::delete_many()
        .filter(user_account::Column::UserId.eq(user_id))
        .exec(&txn)
        .await
        .map_err(|e| async_graphql::Error::new(format!("删除用户账户信息失败: {}", e)))?;

    // 2. 删除用户地址信息
    user_address::Entity::delete_many()
        .filter(user_address::Column::UserId.eq(user_id))
        .exec(&txn)
        .await
        .map_err(|e| async_graphql::Error::new(format!("删除用户地址信息失败: {}", e)))?;

    // 3. 删除用户购物车信息
    user_cart::Entity::delete_many()
        .filter(user_cart::Column::UserId.eq(user_id))
        .exec(&txn)
        .await
        .map_err(|e| async_graphql::Error::new(format!("删除用户购物车信息失败: {}", e)))?;

    // 4. 删除用户收藏信息
    user_collection::Entity::delete_many()
        .filter(user_collection::Column::UserId.eq(user_id))
        .exec(&txn)
        .await
        .map_err(|e| async_graphql::Error::new(format!("删除用户收藏信息失败: {}", e)))?;

    // 5. 删除用户角色关联信息
    user_auth_role::Entity::delete_many()
        .filter(user_auth_role::Column::UserId.eq(user_id))
        .exec(&txn)
        .await
        .map_err(|e| async_graphql::Error::new(format!("删除用户角色信息失败: {}", e)))?;

    // 6. 删除用户权限信息（如果有的话）
    user_auth_authority::Entity::delete_many()
        .filter(user_auth_authority::Column::UserId.eq(user_id))
        .exec(&txn)
        .await
        .map_err(|e| async_graphql::Error::new(format!("删除用户权限信息失败: {}", e)))?;

    // 7. 删除用户钱包信息
    user_wallet::Entity::delete_many()
        .filter(user_wallet::Column::UserId.eq(user_id))
        .exec(&txn)
        .await
        .map_err(|e| async_graphql::Error::new(format!("删除用户钱包信息失败: {}", e)))?;


    // 8. 删除用户钱包账单信息（新增）
    user_wallet_bill::Entity::delete_many()
        .filter(crate::entity::user_wallet_bill::Column::UserId.eq(user_id))
        .exec(&txn)
        .await
        .map_err(|e| async_graphql::Error::new(format!("删除用户钱包账单信息失败: {}", e)))?;

    // 9. 删除用户通知信息（新增）
    user_notification::Entity::delete_many()
        .filter(crate::entity::user_notification::Column::UserId.eq(user_id))
        .exec(&txn)
        .await
        .map_err(|e| async_graphql::Error::new(format!("删除用户通知信息失败: {}", e)))?;


    // 10. 删除用户主信息
    let delete_result = user_main::Entity::delete_by_id(user_id)
        .exec(&txn)
        .await
        .map_err(|e| async_graphql::Error::new(format!("删除用户主信息失败: {}", e)))?;

    // 检查是否成功删除了用户
    if delete_result.rows_affected == 0 {
        txn.rollback().await
            .map_err(|e| async_graphql::Error::new(format!("回滚事务失败: {}", e)))?;
        return Err(async_graphql::Error::new("用户不存在或已被删除"));
    }

    // 提交事务
    txn.commit().await
        .map_err(|e| async_graphql::Error::new(format!("提交事务失败: {}", e)))?;

    // 从Redis中删除用户的登录信息
    let redis_key = format!("user:login:{}", user_id);

    // 使用low-level命令删除Redis中的用户登录信息
    redis::cmd("DEL")
        .arg(&redis_key)
        .query_async::<()>(&mut conn.clone())
        .await
        .map_err(|e| async_graphql::Error::new(format!("删除Redis登录信息失败: {}", e)))?;

    Ok(true)
}


// 在 GraphQL resolver 或其他业务逻辑中使用
pub async fn refresh_token_handler(
    db: &DatabaseConnection,
    conn: &MultiplexedConnection,
    refresh_token: &str,
) -> GraphQLResult<UserTokenObject> {
    // 验证refresh_token
    let refresh_claims: RefreshClaims = JwtUtil::validate_token(refresh_token)?;

    // 从redis获取登录信息
    let jti = redis::cmd("GET")
        .arg(format!("user:login:{}", refresh_claims.u))
        .query_async::<u64>(&mut conn.clone())
        .await
        .map_err(|e| async_graphql::Error::new(format!("用户未登录: {}", e)))?;

    if jti != refresh_claims.j {
        return Err(async_graphql::Error::new("Invalid refresh token"));
    }

    // 获取用户的角色和权限
    let roles = user_auth_role::Entity::find()
        .filter(user_auth_role::Column::UserId.eq(refresh_claims.u))
        .all(db)
        .await?
        .into_iter()
        .map(|role| role.name)
        .collect::<HashSet<String>>();

    let authorities = user_auth_authority::Entity::find()
        .filter(user_auth_authority::Column::UserId.eq(refresh_claims.u))
        .all(db)
        .await?
        .into_iter()
        .map(|authority| authority.name)
        .collect::<HashSet<String>>();

    // 生成新的token
    let token = JwtUtil::generate_token(AccessClaims {
        u: refresh_claims.u.clone(),
        a: authorities,
        e: (Utc::now() + Duration::minutes(30)).timestamp() as u32,
    })?;

    // 生成新的refresh_token
    let jti = SnowID::new(1)?.generate();

    let two_days_later = (Utc::now() + Duration::days(2)).timestamp() as u32;
    let refresh_token = if refresh_claims.expires_at() < two_days_later {
        Some((JwtUtil::generate_token(RefreshClaims {
            u: refresh_claims.u.clone(),
            e: (Utc::now() + Duration::days(7)).timestamp() as u32,
            j: jti.clone(),
        })?, jti))
    } else {
        None
    };


    match refresh_token {
        Some((refresh_token, jti)) => {
            // 保存用户登录信息到Redis
            redis::cmd("SET")
                .arg(format!("user:login:{}", refresh_claims.u))
                .arg(jti)
                .query_async::<()>(&mut conn.clone())
                .await
                .map_err(|e| async_graphql::Error::new(format!("保存用户登录信息失败: {}", e)))?;
            Ok(UserTokenObject {
                access_token: token,
                refresh_token: Some(refresh_token),
            })
        }
        None => {
            Ok(UserTokenObject {
                access_token: token,
                refresh_token: None,
            })
        }
    }

}

/// 该函数负责：
/// 1. 从 Redis 中删除用户的登录状态
/// 2. 使当前的 refresh token 失效
/// 3. 清除相关的会话数据
pub async fn logout(
    db: &DatabaseConnection,
    conn: &MultiplexedConnection,
    user_id: u64,
) -> GraphQLResult<bool> {
    // 构建 Redis key
    let redis_key = format!("user:login:{}", user_id);

    // 添加用户登出标记，有效期30分钟（1800秒）
    let logout_key = format!("user:logout:{}", user_id);
    let expire_seconds = 30 * 60; // 30分钟

    // 使用 Redis SETEX 命令设置带过期时间的 key
    redis::cmd("SETEX")
        .arg(&logout_key)
        .arg(expire_seconds)
        .arg(user_id.to_string()) // 将用户ID作为值存储
        .query_async::<()>(&mut conn.clone())
        .await
        .map_err(|e| async_graphql::Error::new(format!("设置用户登出标记失败: {}", e)))?;


    // 从 Redis 中删除用户的登录信息
    let deleted: u64 = redis::cmd("DEL")
        .arg(&redis_key)
        .query_async(&mut conn.clone())
        .await
        .map_err(|e| async_graphql::Error::new(format!("登出失败: {}", e)))?;

    // 检查是否有数据被删除（可选的日志记录）
    if deleted > 0 {
        debug!("用户 {} 已成功登出", user_id);
    } else {
        warn!("用户 {} 登出时未找到登录信息", user_id);
    }


    Ok(true)
}


// 更新用户信息
pub async fn update_user_info(
    db: &DatabaseConnection,
    id: String,
    nick_name: Option<String>,
    avatar_addr: Option<String>,
    status: Option<String>,
) -> GraphQLResult<bool> {

    let id: u64 = id.parse().map_err(|_| async_graphql::Error::new("无效的用户ID"))?;

    // 检查用户是否存在
    let existing_user = user_main::Entity::find_by_id(id)
        .one(db)
        .await
        .map_err(|e| async_graphql::Error::new(format!("查询用户信息失败: {}", e)))?;

    let user = match existing_user {
        Some(user) => user,
        None => return Err(async_graphql::Error::new("用户不存在")),
    };

    // 更新用户主信息
    let now = Utc::now().naive_utc();
    let user_model = user_main::ActiveModel {
        id: Set(id),
        nickname: Set(nick_name.unwrap_or(user.nickname)),
        avatar_addr: Set(avatar_addr.unwrap_or(user.avatar_addr)),
        status: Set(status.unwrap_or(user.status)),
        update_time: Set(now),
        ..Default::default()
    };

    let updated_user = user_main::Entity::update(user_model)
        .exec(db)
        .await
        .map_err(|e| async_graphql::Error::new(format!("更新用户信息失败: {}", e)))?;


    // 构建返回对象
    Ok(true)
}


// 新增用户账户
pub async fn add_user_account(
    db: &DatabaseConnection,
    user_id: u64,
    account_input: UserAccountInput,
) -> GraphQLResult<UserAccountObject> {
    // 检查用户是否存在
    let existing_user = user_main::Entity::find_by_id(user_id)
        .one(db)
        .await
        .map_err(|e| async_graphql::Error::new(format!("查询用户信息失败: {}", e)))?;

    if existing_user.is_none() {
        return Err(async_graphql::Error::new("用户不存在"));
    }

    // 检查是否已存在相同类型的账户
    let existing_account = user_account::Entity::find()
        .filter(user_account::Column::UserId.eq(user_id))
        .filter(user_account::Column::Type.eq(&account_input.r#type))
        .filter(user_account::Column::Account.eq(&account_input.account))
        .one(db)
        .await
        .map_err(|e| async_graphql::Error::new(format!("查询账户信息失败: {}", e)))?;

    if existing_account.is_some() {
        return Err(async_graphql::Error::new(format!("用户已存在类型为 {} 的账户: {}",
                                                     account_input.r#type, account_input.account)));
    }

    // 创建新账户
    let now = chrono::Utc::now().naive_utc();
    let account_model = user_account::ActiveModel {
        id: Set(SnowID::new(1)?.generate()),
        user_id: Set(user_id),
        r#type: Set(account_input.r#type),
        account: Set(account_input.account),
        access_code: Set(account_input.access_code),
        create_time: Set(now),
        update_time: Set(now),
    };

    let inserted_account = user_account::Entity::insert(account_model)
        .exec_with_returning(db)
        .await
        .map_err(|e| async_graphql::Error::new(format!("创建用户账户失败: {}", e)))?;

    // 构建返回对象
    Ok(UserAccountObject::from(inserted_account))
}


// 删除用户账户
pub async fn delete_user_account(
    db: &DatabaseConnection,
    user_id: u64,
    account_id: String,
) -> GraphQLResult<bool> {
    // 检查用户是否存在
    let existing_user = user_main::Entity::find_by_id(user_id)
        .one(db)
        .await
        .map_err(|e| async_graphql::Error::new(format!("查询用户信息失败: {}", e)))?;

    if existing_user.is_none() {
        return Err(async_graphql::Error::new("用户不存在"));
    }

    let account_id: u64 = account_id.parse().map_err(|_| async_graphql::Error::new("无效的账户ID"))?;

    // 检查账户是否存在且属于该用户
    let existing_account = user_account::Entity::find_by_id(account_id)
        .filter(user_account::Column::UserId.eq(user_id))
        .one(db)
        .await
        .map_err(|e| async_graphql::Error::new(format!("查询账户信息失败: {}", e)))?;

    if existing_account.is_none() {
        return Err(async_graphql::Error::new("账户不存在或不属于该用户"));
    }

    // 删除账户
    let result = user_account::Entity::delete_by_id(account_id)
        .exec(db)
        .await
        .map_err(|e| async_graphql::Error::new(format!("删除用户账户失败: {}", e)))?;

    // 返回是否成功删除
    Ok(result.rows_affected > 0)
}

// 新增用户地址
pub async fn add_user_address(
    db: &DatabaseConnection,
    user_id: u64,
    address_input: UserAddressInput,
) -> GraphQLResult<UserAddressObject> {
    // 检查用户是否存在
    let existing_user = user_main::Entity::find_by_id(user_id)
        .one(db)
        .await
        .map_err(|e| async_graphql::Error::new(format!("查询用户信息失败: {}", e)))?;

    if existing_user.is_none() {
        return Err(async_graphql::Error::new("用户不存在"));
    }

    // 如果设置为默认地址，需要将其他地址设为非默认
    let now = chrono::Utc::now().naive_utc();

    if address_input.is_default {
        user_address::Entity::update_many()
            .filter(user_address::Column::UserId.eq(user_id))
            .filter(user_address::Column::IsDefault.eq(1))
            .set(user_address::ActiveModel {
                is_default: Set(0),
                update_time: Set(now),
                ..Default::default()
            })
            .exec(db)
            .await
            .map_err(|e| async_graphql::Error::new(format!("更新其他地址为非默认失败: {}", e)))?;
    }

    // 创建新地址
    let address_model = user_address::ActiveModel {
        id: Set(SnowID::new(1)?.generate()),
        user_id: Set(user_id),
        recipient_name: Set(address_input.recipient_name),
        phone: Set(address_input.phone),
        province: Set(address_input.province),
        city: Set(address_input.city),
        district: Set(address_input.district),
        detail: Set(address_input.detail),
        is_default: Set(if address_input.is_default { 1 } else { 0 }),
        create_time: Set(now),
        update_time: Set(now),
        tag: Set(address_input.tag),
        province_code: Set(None),
        city_code: Set(None),
        district_code: Set(None),
        remark: Set(None),
    };

    let inserted_address = user_address::Entity::insert(address_model)
        .exec_with_returning(db)
        .await
        .map_err(|e| async_graphql::Error::new(format!("创建用户地址失败: {}", e)))?;

    // 构建返回对象
    Ok(UserAddressObject {
        id: inserted_address.id.to_string(),
        user_id: inserted_address.user_id.to_string(),
        recipient_name: inserted_address.recipient_name,
        phone: inserted_address.phone,
        province: inserted_address.province,
        city: inserted_address.city,
        district: inserted_address.district,
        detail: inserted_address.detail,
        tag: inserted_address.tag,
        is_default: inserted_address.is_default != 0,
        create_time: inserted_address.create_time.format("%Y-%m-%d %H:%M:%S").to_string(),
        update_time: inserted_address.update_time.format("%Y-%m-%d %H:%M:%S").to_string(),
    })
}


// 删除用户地址
pub async fn delete_user_address(
    db: &DatabaseConnection,
    user_id: u64,
    address_id: String,
) -> GraphQLResult<bool> {
    // 检查用户是否存在
    let existing_user = user_main::Entity::find_by_id(user_id)
        .one(db)
        .await
        .map_err(|e| async_graphql::Error::new(format!("查询用户信息失败: {}", e)))?;

    if existing_user.is_none() {
        return Err(async_graphql::Error::new("用户不存在"));
    }

    let address_id: u64 = address_id.parse().map_err(|_| async_graphql::Error::new("无效的地址ID"))?;
    // 检查地址是否存在且属于该用户
    let existing_address = user_address::Entity::find_by_id(address_id)
        .filter(user_address::Column::UserId.eq(user_id))
        .one(db)
        .await
        .map_err(|e| async_graphql::Error::new(format!("查询地址信息失败: {}", e)))?;

    if existing_address.is_none() {
        return Err(async_graphql::Error::new("地址不存在或不属于该用户"));
    }

    // 删除地址
    let result = user_address::Entity::delete_by_id(address_id)
        .exec(db)
        .await
        .map_err(|e| async_graphql::Error::new(format!("删除用户地址失败: {}", e)))?;

    // 返回是否成功删除
    Ok(result.rows_affected > 0)
}



// 更新用户地址
pub async fn update_user_address(
    db: &DatabaseConnection,
    user_id: u64,
    address_id: String,
    address_input: UserAddressInput,
) -> GraphQLResult<UserAddressObject> {
    // 检查用户是否存在
    let existing_user = user_main::Entity::find_by_id(user_id)
        .one(db)
        .await
        .map_err(|e| async_graphql::Error::new(format!("查询用户信息失败: {}", e)))?;

    if existing_user.is_none() {
        return Err(async_graphql::Error::new("用户不存在"));
    }

    let address_id: u64 = address_id.parse().map_err(|_| async_graphql::Error::new("无效的地址ID"))?;

    // 检查地址是否存在且属于该用户
    let existing_address = user_address::Entity::find_by_id(address_id)
        .filter(user_address::Column::UserId.eq(user_id))
        .one(db)
        .await
        .map_err(|e| async_graphql::Error::new(format!("查询地址信息失败: {}", e)))?;

    if existing_address.is_none() {
        return Err(async_graphql::Error::new("地址不存在或不属于该用户"));
    }

    // 如果设置为默认地址，需要将其他地址设为非默认
    let now = chrono::Utc::now().naive_utc();

    if address_input.is_default {
        user_address::Entity::update_many()
            .filter(user_address::Column::UserId.eq(user_id))
            .filter(user_address::Column::IsDefault.eq(1))
            .set(user_address::ActiveModel {
                is_default: Set(0),
                update_time: Set(now),
                ..Default::default()
            })
            .exec(db)
            .await
            .map_err(|e| async_graphql::Error::new(format!("更新其他地址为非默认失败: {}", e)))?;
    }

    // 更新地址
    let address_model = user_address::ActiveModel {
        id: Set(address_id),
        recipient_name: Set(address_input.recipient_name),
        phone: Set(address_input.phone),
        province: Set(address_input.province),
        city: Set(address_input.city),
        district: Set(address_input.district),
        detail: Set(address_input.detail),
        tag: Set(address_input.tag),
        is_default: Set(if address_input.is_default { 1 } else { 0 }),
        update_time: Set(now),
        ..Default::default()
    };

    let updated_address = user_address::Entity::update(address_model)
        .exec(db)
        .await
        .map_err(|e| async_graphql::Error::new(format!("更新用户地址失败: {}", e)))?;

    // 构建返回对象
    Ok(UserAddressObject {
        id: updated_address.id.to_string(),
        user_id: updated_address.user_id.to_string(),
        recipient_name: updated_address.recipient_name,
        phone: updated_address.phone,
        province: updated_address.province,
        city: updated_address.city,
        district: updated_address.district,
        detail: updated_address.detail,
        tag: updated_address.tag,
        is_default: updated_address.is_default != 0,
        create_time: updated_address.create_time.format("%Y-%m-%d %H:%M:%S").to_string(),
        update_time: updated_address.update_time.format("%Y-%m-%d %H:%M:%S").to_string(),
    })
}


// 新增用户购物车商品
pub async fn add_user_cart_item(
    db: &DatabaseConnection,
    user_id: u64,
    product_id: String,
    quantity: u32,
) -> GraphQLResult<UserCartItemObject> {

    let product_id: u64 = product_id.parse().map_err(|_| async_graphql::Error::new("无效的商品ID"))?;

    // 检查用户是否存在
    let existing_user = user_main::Entity::find_by_id(user_id)
        .one(db)
        .await
        .map_err(|e| async_graphql::Error::new(format!("查询用户信息失败: {}", e)))?;

    if existing_user.is_none() {
        return Err(async_graphql::Error::new("用户不存在"));
    }

    // 检查是否已存在该商品在购物车中
    let existing_cart_item = user_cart::Entity::find()
        .filter(user_cart::Column::UserId.eq(user_id))
        .filter(user_cart::Column::ProductId.eq(product_id))
        .one(db)
        .await
        .map_err(|e| async_graphql::Error::new(format!("查询购物车商品失败: {}", e)))?;

    let now = chrono::Utc::now().naive_utc();

    let cart_item: user_cart::Model = if let Some(existing_item) = existing_cart_item {
        // 如果已存在，更新数量
        let new_quantity = existing_item.quantity + quantity;
        let cart_model = user_cart::ActiveModel {
            id: Set(existing_item.id),
            quantity: Set(new_quantity),
            update_time: Set(now),
            ..Default::default()
        };

        user_cart::Entity::update(cart_model)
            .exec(db)
            .await
            .map_err(|e| async_graphql::Error::new(format!("更新用户地址失败: {}", e)))?;

        // 然后重新查询一次更新后的数据（因为 exec 不返回模型）
        user_cart::Entity::find_by_id(existing_item.id)
            .one(db)
            .await
            .map_err(|e| async_graphql::Error::new(format!("查询更新后地址信息失败: {}", e)))?
            .ok_or_else(|| async_graphql::Error::new("地址更新后查询失败"))?

    } else {
        // 如果不存在，创建新记录
        let cart_model = user_cart::ActiveModel {
            id: Set(SnowID::new(1)?.generate()),
            user_id: Set(user_id),
            product_id: Set(product_id),
            quantity: Set(quantity),
            create_time: Set(now),
            update_time: Set(now),
        };

        user_cart::Entity::insert(cart_model)
            .exec_with_returning(db)
            .await
            .map_err(|e| async_graphql::Error::new(format!("添加购物车商品失败: {}", e)))?
    };

    // 构建返回对象
    Ok(UserCartItemObject {
        id: cart_item.id.to_string(),
        user_id: cart_item.user_id.to_string(),
        product_id: cart_item.product_id.to_string(),
        quantity: cart_item.quantity,
        create_time: cart_item.create_time.format("%Y-%m-%d %H:%M:%S").to_string(),
        update_time: cart_item.update_time.format("%Y-%m-%d %H:%M:%S").to_string(),
    })
}


// 更新用户购物车商品数量
pub async fn update_user_cart_item(
    db: &DatabaseConnection,
    user_id: u64,
    cart_item_id: String,
    quantity: u32,
) -> GraphQLResult<UserCartItemObject> {

    let cart_item_id: u64 = cart_item_id.parse().map_err(|_| async_graphql::Error::new("无效的购物车商品ID"))?;

    // 检查用户是否存在
    let existing_user = user_main::Entity::find_by_id(user_id)
        .one(db)
        .await
        .map_err(|e| async_graphql::Error::new(format!("查询用户信息失败: {}", e)))?;

    if existing_user.is_none() {
        return Err(async_graphql::Error::new("用户不存在"));
    }

    // 检查购物车商品是否存在且属于该用户
    let existing_cart_item = user_cart::Entity::find_by_id(cart_item_id)
        .filter(user_cart::Column::UserId.eq(user_id))
        .one(db)
        .await
        .map_err(|e| async_graphql::Error::new(format!("查询购物车商品失败: {}", e)))?;

    let cart_item = match existing_cart_item {
        Some(item) => item,
        None => return Err(async_graphql::Error::new("购物车商品不存在或不属于该用户")),
    };

    // 更新购物车商品数量
    let now = chrono::Utc::now().naive_utc();
    let cart_model = user_cart::ActiveModel {
        id: Set(cart_item_id),
        quantity: Set(quantity),
        update_time: Set(now),
        ..Default::default()
    };

    user_cart::Entity::update(cart_model)
        .exec(db)
        .await
        .map_err(|e| async_graphql::Error::new(format!("更新购物车商品失败: {}", e)))?;

    // 重新查询更新后的数据
    let updated_cart_item = user_cart::Entity::find_by_id(cart_item_id)
        .one(db)
        .await
        .map_err(|e| async_graphql::Error::new(format!("查询更新后购物车商品失败: {}", e)))?
        .ok_or_else(|| async_graphql::Error::new("购物车商品更新后查询失败"))?;

    // 构建返回对象
    Ok(UserCartItemObject {
        id: updated_cart_item.id.to_string(),
        user_id: updated_cart_item.user_id.to_string(),
        product_id: updated_cart_item.product_id.to_string(),
        quantity: updated_cart_item.quantity,
        create_time: updated_cart_item.create_time.format("%Y-%m-%d %H:%M:%S").to_string(),
        update_time: updated_cart_item.update_time.format("%Y-%m-%d %H:%M:%S").to_string(),
    })
}


// 删除用户购物车商品
pub async fn delete_user_cart_item(
    db: &DatabaseConnection,
    user_id: u64,
    cart_item_id: String,
) -> GraphQLResult<bool> {

    let cart_item_id: u64 = cart_item_id.parse().map_err(|_| async_graphql::Error::new("无效的购物车商品ID"))?;

    // 检查用户是否存在
    let existing_user = user_main::Entity::find_by_id(user_id)
        .one(db)
        .await
        .map_err(|e| async_graphql::Error::new(format!("查询用户信息失败: {}", e)))?;

    if existing_user.is_none() {
        return Err(async_graphql::Error::new("用户不存在"));
    }

    // 检查购物车商品是否存在且属于该用户
    let existing_cart_item = user_cart::Entity::find_by_id(cart_item_id)
        .filter(user_cart::Column::UserId.eq(user_id))
        .one(db)
        .await
        .map_err(|e| async_graphql::Error::new(format!("查询购物车商品失败: {}", e)))?;

    if existing_cart_item.is_none() {
        return Err(async_graphql::Error::new("购物车商品不存在或不属于该用户"));
    }

    // 删除购物车商品
    let result = user_cart::Entity::delete_by_id(cart_item_id)
        .exec(db)
        .await
        .map_err(|e| async_graphql::Error::new(format!("删除购物车商品失败: {}", e)))?;

    // 返回是否成功删除
    Ok(result.rows_affected > 0)
}


// 新增用户收藏商品
pub async fn add_user_collection(
    db: &DatabaseConnection,
    user_id: u64,
    product_id: String,
) -> GraphQLResult<UserCollectionObject> {

    let product_id: u64 = product_id.parse().map_err(|_| async_graphql::Error::new("无效的商品ID"))?;

    // 检查用户是否存在
    let existing_user = user_main::Entity::find_by_id(user_id)
        .one(db)
        .await
        .map_err(|e| async_graphql::Error::new(format!("查询用户信息失败: {}", e)))?;

    if existing_user.is_none() {
        return Err(async_graphql::Error::new("用户不存在"));
    }

    // 检查是否已收藏该商品
    let existing_collection = user_collection::Entity::find()
        .filter(user_collection::Column::UserId.eq(user_id))
        .filter(user_collection::Column::ProductId.eq(product_id))
        .one(db)
        .await
        .map_err(|e| async_graphql::Error::new(format!("查询收藏商品失败: {}", e)))?;

    if existing_collection.is_some() {
        return Err(async_graphql::Error::new("商品已在收藏夹中"));
    }

    // 创建新收藏记录
    let now = chrono::Utc::now().naive_utc();
    let collection_model = user_collection::ActiveModel {
        id: Set(SnowID::new(1)?.generate()),
        user_id: Set(user_id),
        product_id: Set(product_id),
        create_time: Set(now),
        update_time: Set(now),
    };

    let inserted_collection = user_collection::Entity::insert(collection_model)
        .exec_with_returning(db)
        .await
        .map_err(|e| async_graphql::Error::new(format!("添加收藏商品失败: {}", e)))?;

    // 构建返回对象
    Ok(UserCollectionObject {
        id: inserted_collection.id.to_string(),
        user_id: inserted_collection.user_id.to_string(),
        product_id: inserted_collection.product_id.to_string(),
        create_time: inserted_collection.create_time.format("%Y-%m-%d %H:%M:%S").to_string(),
        update_time: inserted_collection.update_time.format("%Y-%m-%d %H:%M:%S").to_string(),
    })
}

// 删除用户收藏商品
pub async fn delete_user_collection(
    db: &DatabaseConnection,
    user_id: u64,
    collection_id: String,
) -> GraphQLResult<bool> {

    let collection_id: u64 = collection_id.parse().map_err(|_| async_graphql::Error::new("无效的收藏商品ID"))?;

    // 检查用户是否存在
    let existing_user = user_main::Entity::find_by_id(user_id)
        .one(db)
        .await
        .map_err(|e| async_graphql::Error::new(format!("查询用户信息失败: {}", e)))?;

    if existing_user.is_none() {
        return Err(async_graphql::Error::new("用户不存在"));
    }

    // 检查收藏商品是否存在且属于该用户
    let existing_collection = user_collection::Entity::find_by_id(collection_id)
        .filter(user_collection::Column::UserId.eq(user_id))
        .one(db)
        .await
        .map_err(|e| async_graphql::Error::new(format!("查询收藏商品失败: {}", e)))?;

    if existing_collection.is_none() {
        return Err(async_graphql::Error::new("收藏商品不存在或不属于该用户"));
    }

    // 删除收藏商品
    let result = user_collection::Entity::delete_by_id(collection_id)
        .exec(db)
        .await
        .map_err(|e| async_graphql::Error::new(format!("删除收藏商品失败: {}", e)))?;

    // 返回是否成功删除
    Ok(result.rows_affected > 0)
}

// 开通用户钱包
pub async fn open_user_wallet(
    db: &DatabaseConnection,
    user_id: u64,
    pay_password: String
) -> GraphQLResult<UserWalletObject> {
    // 检查用户是否存在
    let existing_user = user_main::Entity::find_by_id(user_id)
        .one(db)
        .await
        .map_err(|e| async_graphql::Error::new(format!("查询用户信息失败: {}", e)))?;

    if existing_user.is_none() {
        return Err(async_graphql::Error::new("用户不存在"));
    }

    // 检查用户是否已有钱包
    let existing_wallet = user_wallet::Entity::find()
        .filter(user_wallet::Column::UserId.eq(user_id))
        .one(db)
        .await
        .map_err(|e| async_graphql::Error::new(format!("查询用户钱包失败: {}", e)))?;

    if existing_wallet.is_some() {
        return Err(async_graphql::Error::new("用户已开通钱包"));
    }

    // 生成盐值并哈希密码
    let salt = SaltString::generate(&mut OsRng);
    let argon2 = Argon2::default();
    let password_hash = argon2
        .hash_password(pay_password.as_bytes(), &salt)
        .map_err(|e| async_graphql::Error::new(format!("密码处理失败: {}", e)))?
        .to_string();
    // 创建新钱包，初始余额为0
    let now = chrono::Utc::now().naive_utc();
    let wallet_model = user_wallet::ActiveModel {
        id: Set(SnowID::new(1)?.generate()),
        user_id: Set(user_id),
        balance: Set(Decimal::ZERO), // 初始余额为0
        pay_password: Set(password_hash),
        frozen_balance: Set(Decimal::ZERO),
        create_time: Set(now),
        update_time: Set(now),
    };

    let inserted_wallet = user_wallet::Entity::insert(wallet_model)
        .exec_with_returning(db)
        .await
        .map_err(|e| async_graphql::Error::new(format!("创建用户钱包失败: {}", e)))?;

    // 构建返回对象
    Ok(UserWalletObject {
        id: inserted_wallet.id.to_string(),
        user_id: inserted_wallet.user_id.to_string(),
        balance: inserted_wallet.balance.to_string(),
        create_time: inserted_wallet.create_time.format("%Y-%m-%d %H:%M:%S").to_string(),
        update_time: inserted_wallet.update_time.format("%Y-%m-%d %H:%M:%S").to_string(),
    })
}


// 钱包充值
pub async fn recharge_user_wallet(
    db: &DatabaseConnection,
    user_id: u64,
    amount: Decimal,
    channel_type: String,
    channel_id: String,
    pay_password: String,
) -> GraphQLResult<UserWalletObject> {

    // 检查用户是否存在
    let existing_user = user_main::Entity::find_by_id(user_id)
        .one(db)
        .await
        .map_err(|e| async_graphql::Error::new(format!("查询用户信息失败: {}", e)))?;

    if existing_user.is_none() {
        return Err(async_graphql::Error::new("用户不存在"));
    }

    // 检查用户是否有钱包
    let existing_wallet = user_wallet::Entity::find()
        .filter(user_wallet::Column::UserId.eq(user_id))
        .one(db)
        .await
        .map_err(|e| async_graphql::Error::new(format!("查询用户钱包失败: {}", e)))?;

    let wallet = match existing_wallet {
        Some(wallet) => wallet,
        None => return Err(async_graphql::Error::new("用户未开通钱包")),
    };



    let parsed_hash = PasswordHash::new(&wallet.pay_password)
        .map_err(|_| async_graphql::Error::new("支付密码格式错误"))?;

    let argon2 = Argon2::default();
    argon2
        .verify_password(pay_password.as_bytes(), &parsed_hash)
        .map_err(|_| async_graphql::Error::new("支付密码错误"))?;

    // 开启事务
    let txn = db.begin().await
        .map_err(|e| async_graphql::Error::new(format!("开启事务失败: {}", e)))?;

    // 创建充值账单记录
    let now = chrono::Utc::now().naive_utc();
    let bill_model = user_wallet_bill::ActiveModel {
        id: Set(SnowID::new(1)?.generate()),
        create_time: Set(now),
        update_time: Set(now),
        user_id: Set(user_id),
        user_wallet_id: Set(wallet.id),
        channel_type: Set(channel_type),
        channel_id: Set(channel_id.parse()?),
        money: Set(amount),
        status: Set("recharge".to_string()), // 假设充值直接成功
    };

    user_wallet_bill::Entity::insert(bill_model)
        .exec(&txn)
        .await
        .map_err(|e| async_graphql::Error::new(format!("创建充值账单失败: {}", e)))?;

    // 更新钱包余额
    let new_balance = wallet.balance + amount;
    let wallet_model = user_wallet::ActiveModel {
        id: Set(wallet.id),
        balance: Set(new_balance),
        update_time: Set(now),
        ..Default::default()
    };

    let updated_wallet = user_wallet::Entity::update(wallet_model)
        .exec(&txn)
        .await
        .map_err(|e| async_graphql::Error::new(format!("更新钱包余额失败: {}", e)))?;

    // 提交事务
    txn.commit().await
        .map_err(|e| async_graphql::Error::new(format!("提交事务失败: {}", e)))?;

    // 构建返回对象
    Ok(UserWalletObject {
        id: updated_wallet.id.to_string(),
        user_id: updated_wallet.user_id.to_string(),
        balance: updated_wallet.balance.to_string(),
        create_time: updated_wallet.create_time.format("%Y-%m-%d %H:%M:%S").to_string(),
        update_time: updated_wallet.update_time.format("%Y-%m-%d %H:%M:%S").to_string(),
    })
}